import React, { useEffect, useState, useRef } from "react";
import { Tabs } from "antd";
import { useNavigate, useMatches } from "react-router-dom";

const HistoryNavigator = () => {
  const [historyStack, setHistoryStack] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(-1);
  const matches = useMatches(); // 获取所有匹配的路由层级
  const navigate = useNavigate();
  const isFirstRender = useRef(true);
  const lastPath = useRef("");

  // 从matches中获取当前页面的路由信息（最深层的匹配项）
  const currentRoute = matches[matches.length - 1]; // 最后一项是当前页面路由
  const currentPath = currentRoute?.pathname || ""; // 当前路径

  // 记录路由历史
  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      lastPath.current = currentPath;

      // 初始化历史记录（可从路由元信息取标题）
      setHistoryStack([
        {
          key: currentPath,
          path: currentPath,
          // 优先使用路由元信息的title，其次是页面标题，最后是路径
          label: currentRoute?.handle?.title || document.title || currentPath,
        },
      ]);
      setCurrentIndex(0);
      return;
    }

    // 路径未变化则不处理
    if (currentPath === lastPath.current) return;

    // 检查是否为重复路由
    const isDuplicate = historyStack.some((item) => item?.path === currentPath);

    if (!isDuplicate) {
    //   const newHistory = historyStack.slice(0, currentIndex + 1);
     const newHistory = historyStack
      newHistory.push({
        key: currentPath,
        path: currentPath,
        label: currentRoute?.handle?.title || document.title || currentPath,
      });

      setHistoryStack(newHistory);
      setCurrentIndex(newHistory.length - 1);
    } else {
      setCurrentIndex(
        historyStack.findIndex((item) => item?.key === currentPath)
      );
    }

    lastPath.current = currentPath;
  }, [currentPath, currentIndex, historyStack, currentRoute?.handle?.title]);
  // 依赖currentPath（而非location.pathname）和路由标题

  // 标签切换时跳转路由
  const onChange = (key) => {
    const targetItem = historyStack.find((item) => item?.key === key);
    if (targetItem) {
      navigate(targetItem.path);
      setCurrentIndex(historyStack.findIndex((item) => item?.key === key));
    }
  };

  // 处理标签删除
  const onEdit = (key, action) => {
    if (action === "remove") {
      const newStack = historyStack.filter((item) => item?.key !== key);
      setHistoryStack(newStack);

      if (key === historyStack[currentIndex]?.key) {
        const newIndex = Math.max(0, newStack.length - 1);
        setCurrentIndex(newIndex);
        if (newStack[newIndex]) {
          navigate(newStack[newIndex].path);
        }
      }
    }
  };

  return (
      <Tabs
        hideAdd={true}
        onChange={onChange}
        activeKey={historyStack[currentIndex]?.key}
        type="editable-card"
        style={{ marginBottom: 0 }}
        onEdit={onEdit}
        items={historyStack.filter(Boolean).map((item) => ({
          key: item.key,
          label: item.label,
        }))}
      />
  );
};

export default HistoryNavigator;
